<template>
  <div class="container">
    <input type="file" accept=".xls,.xlsx" class="upload_file" @change="handleUpload($event)" />
  </div>
</template>

<script>
// https://www.jianshu.com/p/0af7c97b4bcf
import excel from '@/util/complierExcel'
export default {
  methods: {
    handleUpload(e) {
      debugger
      console.log(e)
      const input = e.target
      console.log(input)
      const files = e.target.files
      let file = files[0]
      console.log(file)
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件转换json
    readFile(file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = (e) => {
        this.tableLoading = true
      }
      reader.onprogress = (e) => {
        this.progressPercent = Math.round((e.loaded / e.total) * 100)
      }
      reader.onerror = (e) => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = (e) => {
        console.log(excel, 'excel')
        const data = e.target.result
        excel.read2(data, 'binary')
                
                
        const { header, results } = excel.read(data, 'array')

        const tableTitle = header.map((item) => {
          return { title: item, key: item }
        })
        //这里的tableData就是拿到的excel表格中的数据
        console.log(header)
        console.log(results)
        console.log(tableTitle)
        this.tableData = results
        this.tableTitle = tableTitle
        const map = new Map()
        header.map((key) => {
          let arr = new Array()
          results.map((v) => {
            arr.push(v[key])
          })
          map.set(key, arr)
        })
        // results.forEach(title=>{
        //
        // })
        console.log(map)
        console.log(map.get('ID'))
        this.tableLoading = false
      }
    }
  }
}
</script>